<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/header.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/comp.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/fcs.php');
?>

</script>

<?php
if(isset($_GET['task']))
{
		if(!$link=mysql_connect("localhost",$user,$pass))
			die("Error in Database Connection");

		if(!mysql_select_db("bs"))
			echo("Error in Database Selection");

		if($_GET['task']=="addform")
		{
?>

				-> <a href="trans.php">Transaction </a> -><a href="contra_trans.php?task=addform"> Contra </a>	<br />
				<h3>Contra Entry</h3>
				<table class="main">
				<form name="addform" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
				<tr><td><label>By (Debit) : Ledger </label> </td><td><select name="ldname">
<?php
				//DIPLAY ALL LEDGER ONLY CASH OR BANK
				$resultmain=mysql_query("select * from bs_groups where under='00'");
				if(!$resultmain)
						echo("Error in Query Execution");
				while($arrmain=mysql_fetch_array($resultmain))
				{
						extract_ledger_cash_bank_with_balance($arrmain['id']);
				}
?>
				</select></td></tr>
				<tr><td><label>To (Credit) : Ledger </label> </td><td><select name="pldname">
<?php
				//DIPLAY ALL LEDGER ONLY CASH OR BANK
				$resultmain=mysql_query("select * from bs_groups where under='00'");
				if(!$resultmain)
						echo("Error in Query Execution");
				while($arrmain=mysql_fetch_array($resultmain))
				{
						extract_ledger_cash_bank_with_balance($arrmain['id']);
				}
?>
				</select></td></tr>
				<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo date("d-m-Y");?>" /></td></tr>
				<tr><td><label>Amount</label></td><td><input type="text" name="amount" value="0" /> Rs</td></tr>
				<tr><td><label>Description</label></td><td><textarea name="desc" rows="4"></textarea></td></tr>
				<tr><td><input type="submit" value="Add" /></td></tr>
				<input type="hidden" name="task" value="add" />
				</form>
				</table>
		
<?php
			}//END OF TASK= ADD
			
		if($_GET['task']=="edit_form")
		{

				$pid=$_GET['pid'];

				$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_contra_book where id='{$pid}'");
				if(!$result)
					echo("Error in Query Execution");
				$arr=mysql_fetch_array($result);
		
				$date=$arr['date'];
				$amount=(int)$arr['amount'];
				$description=$arr['description'];
				$pldid=$arr['credit_ledger_id'];						
				$ldid=$arr['debit_ledger_id'];
		
		
?>

				| <a href="trans.php">Transaction </a> | <a href="contra_trans.php?task=addform"> Contra </a>	</div>
				<h3>Edit Contra Entry | <a href="contra_trans.php?task=delete&pid=<?php echo $pid?>">Delete</a></h3>
				<table class="main">
				<form name="addform" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
				<tr><td><label>By (Debit) : Ledger </label> </td><td><select name="ldid">
<?php
				//DIPLAY ALL LEDGER ONLY CASH OR BANK
				$resultmain=mysql_query("select * from bs_groups where under='00'");
				if(!$resultmain)
						echo("Error in Query Execution");
				while($arrmain=mysql_fetch_array($resultmain))
				{
						extract_ledger_cash_bank_with_balance_wc($arrmain['id'],$ldid);
				}
?>
				</select></td></tr>
				<tr><td><label>To (Credit) : Ledger </label> </td><td><select name="pldid">
<?php
				//DIPLAY ALL LEDGER ONLY CASH OR BANK
				$resultmain=mysql_query("select * from bs_groups where under='00'");
				if(!$resultmain)
						echo("Error in Query Execution");
				while($arrmain=mysql_fetch_array($resultmain))
				{
						extract_ledger_cash_bank_with_balance_wc($arrmain['id'],$pldid);
				}
?>
				</select></td></tr>
				<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo $date?>" /></td></tr>
				<tr><td><label>Amount</label></td><td><input type="text" name="amount" value="<?php echo $amount?>" /> Rs</td></tr>
				<tr><td><label>Description</label></td><td><textarea name="desc" rows="4"><?php echo $description?></textarea></td></tr>
				<tr><td><input type="submit" value="Update" /></td></tr>
				<input type="hidden" name="task" value="edit_add" />
				<input type="hidden" name="pid" value="<?php echo $pid ?>" />				
				</form>
				</table>
		
<?php
			}//END OF TASK= edit
			
				if($_GET['task']=="delete")
	{
?>
		| <a href="trans.php">Transaction </a> | Contra Book</div>
		<h3>Contra Book Transaction Deletion</h3>

<?php	
		$succ=1;
		
		$pid=$_GET['pid'];

		$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_contra_book where id='{$pid}'");
		if(!$result)
				echo("Error in Query Execution");
		$previous=mysql_fetch_array($result);
		
		
		
		//delete in debit_ledger_id

					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['debit_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$ldname} where voucher_type='CONTRA' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$ldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				

		
		//delete in credit_ledger_id
		
					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['credit_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$pldname} where voucher_type='CONTRA' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				
		
		//delete in journal book
						$result=mysql_query("delete from bs_contra_book where id='{$pid}'" );			
						if(!$result)
						{
							echo("Error in contra book deletion".mysql_error());
							$succ=0;
						}
			
		if($succ==1)
			echo"<br>SuccessFul";
		else
			echo"<br>Operation Fail";
			
				
	}//end of delete operation

			
}//END OF ISSET GET

else if(isset($_POST['task']))
{
?>
			-> <a href="trans.php">Transaction </a> -><a href="contra_trans.php?task=addform"> Contra </a>	<br />
			<h3>Contra Entry</h3>

<?php		

		if(!$link=mysql_connect("localhost",$user,$pass))
				die("Error in Database Connection");

		if(!mysql_select_db("bs"))
				echo("Error in Database Selection");
		

				$valid=1;
				// VALIDATE DATE AND AMOUNT
				include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/validate_date_amount.php');		
				
				// AVOID SAME LEDGER IN DEBIT AND CREDIT SIDE
		
			if($_POST['task']=="add")
			{	
				
				if($_POST['ldname']==$_POST['pldname'])
				{
					echo "<br>Debit and Credit Side are Same ! Invalid Input";
					$valid=0;
				}
				
				// AVOID NEGATIVE CASH
				if(!is_negative_cash_allowed($_POST['pldname']))
				{
						$ledger="bs_ledger_".ereg_replace(" ","_",$_POST['pldname']);
						$result=mysql_query("select (SUM(debit)-SUM(credit)) as balance from {$ledger}");
						if(!$result)
								echo "Internal Select Query Error".mysql_error();
						$arr=mysql_fetch_array($result);
				
						$cashbalance=$arr['balance'];
	
						if($cashbalance<$amount)
						{
								echo "<br>Negative Cash Balance in Credit Side: {$cashbalance} Rs. ";
								echo "<br>Negative Cash is not Allowed in Cash and Bank Accounts ";					
								$valid=0;
						}
				}

			}
			else if($_POST['task']=="edit_add")
			{
				if($_POST['ldid']==$_POST['pldid'])
				{
					echo "<br>Debit and Credit Side are Same ! Invalid Input";
					$valid=0;
				}
				
						$pid=$_POST['pid'];
						
								$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_contra_book where id='{$pid}'");
								if(!$result)
										echo("Error in Query Execution");
								$previous=mysql_fetch_array($result);
						$pldid=$previous['credit_ledger_id'];
						$ldid=$previous['debit_ledger_id'];
						
						$new_pldid=$_POST['pldid'];
						
						if($pldid==$new_pldid)
							$plus_this_entry=$previous['amount'];
						else
							$plus_this_entry=0;
						
								$result=mysql_query("select ldname from bs_ledgers where id='{$new_pldid}'");
								if(!$result)
										echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
						$pldname=$arr['ldname'];
						
											
						//---
							//I have to add the amount in balance that is in current entry with pid
						if(!is_negative_cash_allowed($pldname))
						{
								$ledger="bs_ledger_".ereg_replace(" ","_",$pldname);
								$result=mysql_query("select (SUM(debit)-SUM(credit)) as balance from {$ledger}");
								if(!$result)
										echo "Internal Select Query Error".mysql_error();
								$arr=mysql_fetch_array($result);
							
								$cashbalance=$arr['balance']+$plus_this_entry;
	
								if($cashbalance<$amount)
								{
										echo "<br>Negative Cash Balance in Credit Side: {$arr['balance']} Rs. ";
										echo "<br>Negative Cash is not Allowed in Cash and Bank Accounts ";					
										$valid=0;
								}
						}
			
			}
			
			
			
			$succ=0;
				
			if($_POST['task']=="add")
			{	
		
				if($valid==1)
				{
						$succ=1;
			
						//$ldid, $pldid different,,,,,,,,     single contra entry

						//EXTRACTING LDID
						$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['ldname']}'");
						if(!$result)
						{
								echo("Error in Query Execution");
								$succ=0;
						}
						$arr=mysql_fetch_array($result);
			
						$ldid=$arr['id'];
			
		
		
						//EXTRACTING PLDID
						$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['pldname']}'");
						if(!$result)
						{
								echo("Error in Query Execution");
								$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$pldid=$arr['id'];
			
		
				
						//insert into contra book
			
						$result=mysql_query("INSERT INTO `bs_contra_book` (`id`, `debit_ledger_id`, `description`,`amount`, `date`, `credit_ledger_id`) VALUES (NULL,'{$ldid}','{$_POST['desc']}','{$_POST['amount']}','{$date}','{$pldid}')");
						if(!$result)
						{
								echo("Error in contra Book Insertion  ".mysql_error());
									$succ=0;
						}
			
			

						$voucherid=mysql_insert_id();
			
						//credit ledger pldname
						$pldname="bs_ledger_".ereg_replace(" ","_",$_POST['pldname']);
						$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'CONTRA','{$voucherid}', '0.00','{$_POST['amount']}','{$date}')");			
						if(!$result)
						{
								echo("<br>Error in crediting source ledger: ".mysql_error());
								$succ=0;
						}
			

						//debit party ledger =LDID
						$ldname="bs_ledger_".ereg_replace(" ","_",$_POST['ldname']);
						$result=mysql_query("INSERT INTO {$ldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'CONTRA','{$voucherid}', '{$_POST['amount']}','0.00','{$date}')");			
						if(!$result)
						{
								echo("<br>Error in debiting ledger : ".mysql_error());
								$succ=0;
						}
		
				}//END OF VALID =1 
				
			
		}//END OF TASK=ADD
		
			if($_POST['task']=="edit_add")
			{	
			
				//strictly check that there must be no overriding of variables !!!
				
				$pid=$_POST['pid'];

				$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_contra_book where id='{$pid}'");
				if(!$result)
						echo("Error in Query Execution");
				$previous=mysql_fetch_array($result);
		
				
				$ldid=$previous['debit_ledger_id'];
				$pldid=$previous['credit_ledger_id'];
				$new_pldid=$_POST['pldid'];
				$new_ldid=$_POST['ldid'];
				
				

			/*
			if there is any change
			{
				update contra book..			
			
				if change in pldid
				{
					delete from previous pldid
					entry in new pldid
				}
				{
					//no change in pldid
					//but there is another change
					so update in  pldid
				}
				
				if change in ldid
				{
					delete from previous ldid
					entry in new ldid
				}
				{
					//no change in ldid
					//but there is another change
					so update in  ldid
				}
				
				
			}
		*/
		
				$change=1;
				if($previous['date']==$_POST['date'])
				{
						if((int)$previous['amount']==$_POST['amount'])
						{
								if($previous['description']==$_POST['desc'])
								{
										if($ldid==$new_ldid)
										{
									
												if($pldid==$new_pldid)
												{
														$change=0;
														echo "No Alteration Performed!";
												}
										}
								}
						}
				}
							

//				$valid=0;//temp
				if($valid==1 && $change==1)
				{
						$succ=1;
						
								
			
						//$ldid, $pldid different,,,,,,,,     single journal entry
																	
							//same query again! must be global 
	
						//	$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_receipt_book where id='{$pid}'");
		
							//if(!$result)
								//	echo("Error in Query Execution");
//							$previous=mysql_fetch_array($result);
			
							$result=mysql_query("UPDATE `bs_contra_book` as p SET p.debit_ledger_id='{$new_ldid}', p.description='{$_POST['desc']}', p.amount='{$_POST['amount']}' , p.date='{$date}',p.credit_ledger_id='{$new_pldid}' WHERE p.id = '{$pid}' ");
				
							if(!$result)
							{
									echo("Error in contra Book Alteratsion : ".mysql_error());
									$succ=0;
							}
					

			
			
			
							if($previous['debit_ledger_id']!=$new_ldid)
							{
									//delete in one-------add in another
				
				
									//delete from previous
											//1. extract previous ldname
											$result=mysql_query("select ldname from bs_ledgers where id='{$previous['debit_ledger_id']}'");
											if(!$result)
													echo("Error in Query Execution");
											$arr=mysql_fetch_array($result);
											$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
											//2. delete from previous ldname
													//first fetch the id!!!
													$result=mysql_query("select id from {$ldname} where voucher_type='CONTRA' and voucher_id='{$pid}' ");
													if(!$result)
													{
															echo("Error");
															$succ=0;
													}
													$arr=mysql_fetch_array($result);
							
													$result=mysql_query("delete from {$ldname} where id='{$arr['id']}'" );			
													if(!$result)
													{
																echo("Error in previous Ledger deletion".mysql_error());
																$succ=0;
													}				
					
									//add in new (debit source ledger)
									//1. extract new ldname
									$result=mysql_query("select ldname from bs_ledgers where id='{$new_ldid}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
									//2. insert in new 
									//debit ledger
									$result=mysql_query("INSERT INTO {$ldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'CONTRA','{$pid}','{$_POST['amount']}', '0.00','{$date}')");			
									if(!$result)
									{
											echo("Error in Debiting Ledger Insertion".mysql_error());
											$succ=0;
									}
					

					
							}
							else
							{
									//update in one
					
									//1. extract previous=new ldname (debited)
									$result=mysql_query("select ldname from bs_ledgers where id='{$previous['debit_ledger_id']}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
									$result=mysql_query("UPDATE {$ldname} as p SET p.debit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='CONTRA' and p.voucher_id = '{$pid}' LIMIT 1 ");
									if(!$result)
									{
											echo("Error in Debited Alteration");
											$succ=0;
									}
		
							}
							
							//now in pldid
							
							if($previous['credit_ledger_id']!=$new_pldid)
							{
									//delete in one-------add in another
				
				
									//delete from previous
											//1. extract previous ldname
											$result=mysql_query("select ldname from bs_ledgers where id='{$previous['credit_ledger_id']}'");
											if(!$result)
													echo("Error in Query Execution");
											$arr=mysql_fetch_array($result);
											$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
											//2. delete from previous ldname
													//first fetch the id!!!
													$result=mysql_query("select id from {$pldname} where voucher_type='CONTRA' and voucher_id='{$pid}' ");
													if(!$result)
													{
															echo("Error");
															$succ=0;
													}
													$arr=mysql_fetch_array($result);
							
													$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
													if(!$result)
													{
																echo("Error in previous Ledger deletion".mysql_error());
																$succ=0;
													}				
					
									//add in new (credit source ledger)
									//1. extract new ldname
									$result=mysql_query("select ldname from bs_ledgers where id='{$new_pldid}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
									//2. insert in new 
									//debit ledger
									$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'CONTRA','{$pid}', '0.00','{$_POST['amount']}','{$date}')");			
									if(!$result)
									{
											echo("Error in crediting Ledger Insertion".mysql_error());
											$succ=0;
									}
					

					
							}
							else
							{
									//update in one
					
									//1. extract previous=new pldname (credited)
									$result=mysql_query("select ldname from bs_ledgers where id='{$previous['credit_ledger_id']}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
									$result=mysql_query("UPDATE {$pldname} as p SET p.credit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='CONTRA' and p.voucher_id = '{$pid}' LIMIT 1 ");
									if(!$result)
									{
											echo("Error in credited Alteration");
											$succ=0;
									}
		
							}
							


		
				}//END OF valid
				
				
		
			
		}//END OF TASK=edit_add

		
		
				if($succ==1)
					echo"<br>SuccessFul";
				else
					echo"<br>Operation Fail";
		
}//END OF ISSET POST
?>
